import time

import cv2
import subprocess


class CvRtmp:

    def __init__(self,rtmpAddress):
        self.address = rtmpAddress
        self.cap = None
        self.ffmpegProcess = None
        self.isRunning = False

    def start(self):
        self.isRunning = True
        # 打开摄像头
        self.cap = cv2.VideoCapture(0)

        # 设置摄像头分辨率
        self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
        self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
        self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 2)
        # 定义视频编码器
        fourcc = cv2.VideoWriter_fourcc(*'X264')

        # 创建FFmpeg命令行参数
        # 注意如果是在
        ffmpeg_cmd = ['ffmpeg', # ffmpeg安装路径
                      '-y',  # 覆盖已存在的文件
                      '-f', 'rawvideo',
                      '-pixel_format', 'bgr24',
                      '-video_size', '320x240',
                      '-i', '-',  # 从标准输入读取数据
                      '-c:v', 'libx264', #使用x264编码器
                      '-preset', 'ultrafast',
                      '-tune', 'zerolatency',#零延迟
                      '-pix_fmt', 'yuv420p',
                      '-f', 'flv',
                      self.address]

        # 启动FFmpeg进程
        self.ffmpegProcess = subprocess.Popen(ffmpeg_cmd, stdin=subprocess.PIPE)
        # 开始采集和推流
        while self.isRunning:
            # 采集一帧图像
            ret, frame = self.cap.read()
            if ret:
                # 通过FFmpeg编码和推流
                try:
                    self.ffmpegProcess.stdin.write(frame.tobytes())
                    time.sleep(0.1)
                except:
                    print('push stream error')
            else:
                time.sleep(1)

        # 停止FFmpeg进程并释放资源
        self.ffmpegProcess.stdin.close()
        self.ffmpegProcess.wait()
        self.cap.release()
        
        

if __name__ == '__main__':
    #rtmp://vt.qy-cloud.cn.w.kunlunso.com/?auth_key=1715693492-0-0-d16c40542d0bd8dd5bfc2a5c79a36c59
    #rtmp://101.132.123.218:1936/hls
    #rtmp = CvRtmp('rtmp://vt.qy-cloud.cn.w.kunlunso.com/?auth_key=1715693492-0-0-d16c40542d0bd8dd5bfc2a5c79a36c59')
    rtmp = CvRtmp('rtmp://vt.qy-cloud.cn/uds/live?auth_key=1746544575-0-0-ffb2022da670c323204ac06b79b911bc')
    rtmp.start()
    
    
    
    




